﻿package gear.ui.bd {
	import gear.net.AssetData;
	import gear.utils.BDUtil;

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.geom.Point;

	/**
	 * 位图字体
	 * 
	 * @author bright
	 * @version 20101015
	 */
	public final class BDFont extends Sprite {
		private var _chars : Array;
		private var _width : int;
		private var _height : int;
		private var _gap : int;
		private var _bdData : BDData;
		private var _bitmap : Bitmap;
		private var _source : Object;

		/**
		 * Bitmap Data Font 位图字体
		 * 
		 * @param source AssetData
		 * @param chars Array对应的字符数组
		 * @param width int 单位宽
		 * @param height int 单位高
		 * @param gap int 间距
		 * @example 
		 * var bf:BDFont=new BDFont(new AssetData("damage_number"), ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], 11, 15);
		 * bf.x = 10;
		 * bf.y = 10;
		 * addChild(_bf);
		 * bf.text = "1234567890";
		 */
		public function BDFont(source : AssetData, chars : Array, width : int, height : int, gap : int = 0) {
			_chars = chars;
			_width = width;
			_height = height;
			_gap = gap;
			_bdData = BDUtil.cutBD(source, _width, _height);
			_bitmap = new Bitmap();
			addChild(_bitmap);
		}

		/**
		 * 设置文本
		 * 
		 * @param String
		 */
		public function set text(value : String) : void {
			var width : int = _width + _gap;
			var bd : BitmapData = new BitmapData(value.length * width - _gap, _height, true, 0);
			for (var i : int = 0;i < value.length;i++) {
				var unit : String = value.charAt(i);
				var index : int = _chars.indexOf(unit);
				if (index != -1) {
					var cut : BitmapData = _bdData.getBDUnit(index).bd;
					bd.copyPixels(cut, cut.rect, new Point(i * width, 0), null, null, true);
				}
			}
			_bitmap.bitmapData = bd;
		}

		/**
		 * @return 		 */
		override public function get width() : Number {
			return _bitmap.width;
		}

		/**
		 * @return 高度		/
		override public function get height() : Number {
		return _bitmap.height;
		}

		/**
		 * 设置数据源
		 * 
		 * @param value 数据源
		 */
		public function set source(value : *) : void {
			_source = value;
		}

		/**
		 * 获得数据源
		 * 
		 * @return 数据源	 */
		public function get source() : * {
			return _source;
		}

		/**
		 * 清除
		 */
		public function clear() : void {
			if (_bitmap.bitmapData != null) {
				_bitmap.bitmapData.dispose();
				_bitmap.bitmapData = null;
			}
		}
	}
}
